package com.hcryan.djm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hcryan.djm.exception.ErrorMessage;
import com.hcryan.djm.exception.TravelException;
import com.hcryan.djm.http.request.LoginReq;
import com.hcryan.djm.mapper.UserMapper;
import com.hcryan.djm.pojo.entity.User;
import com.hcryan.djm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ryanwdj
 * @since 2025/2/18
 */

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public void register(User user) {
        user.setRegistrationDate(new Date());
        user.setIsVerified(0);
        this.save(user);
    }

    @Override
    public void login(LoginReq req) {
        LambdaQueryWrapper<User>queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, req.getUsername());
        User user = this.getOne(queryWrapper);
        if(user == null){
            throw new TravelException(ErrorMessage.EMPTY_USER);
        }else if(!user.getPassword().equals(req.getPassword())){
            throw new TravelException(ErrorMessage.ERROR_PASSWORD);
        }else{
            updateLastLoginDate(user.getUserId());
        }
    }

    private void updateLastLoginDate(Long userId) {
        LambdaUpdateWrapper<User>updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getUserId, userId)
                .set(User::getLastLoginDate, new Date());
        this.update(updateWrapper);
    }
}
